package com.gqzdev.service.impl;

import com.gqzdev.entity.Blog;
import com.gqzdev.entity.BlogType;
import com.gqzdev.entity.Blogger;
import com.gqzdev.entity.Link;
import com.gqzdev.service.BlogService;
import com.gqzdev.service.BlogTypeService;
import com.gqzdev.service.BloggerService;
import com.gqzdev.service.LinkService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

/**
 * 初始化组件 把博主信息
 * 根据博客  类别分类 根据日期归档分类
 * 存放到application中，用以提供页面请求性能
 * @author Administrator
 *
 */
@Component
public class InitComponent implements ServletContextListener,ApplicationContextAware{

	private static ApplicationContext applicationContext = null;


	/**
	 *  实现ApplicationContextAware接口，重写setApplicationContext自动注入applictionContext
	 */

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		InitComponent.applicationContext=applicationContext;
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		ServletContext application=servletContextEvent.getServletContext();
		// 查询博主信息
		BloggerService bloggerService=(BloggerService) applicationContext.getBean("bloggerService");
		Blogger blogger=bloggerService.find();
		blogger.setPassword(null);
		application.setAttribute("blogger", blogger);

		// 查询博客类别以及博客的数量
		BlogTypeService blogTypeService=(BlogTypeService) applicationContext.getBean("blogTypeService");
		List<BlogType> blogTypeCountList=blogTypeService.countList();
		application.setAttribute("blogTypeCountList", blogTypeCountList);

		// 根据日期分组查询博客
		BlogService blogService=(BlogService) applicationContext.getBean("blogService");
		List<Blog> blogCountList=blogService.countList();
		application.setAttribute("blogCountList", blogCountList);

		// 查询所有的友情链接信息
		LinkService linkService=(LinkService) applicationContext.getBean("linkService");
		List<Link> linkList=linkService.list(null);
		application.setAttribute("linkList", linkList);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}
}
